package edu.office.applicationRepository;

import edu.office.entities.School;
import edu.office.entities.Student;
import edu.office.entities.Studentdream;
import edu.office.entities.Subject;
import edu.office.tools.EOMessage;
import edu.office.tools.EOMessage1;
import edu.office.tools.NLP.WordsSegment;
import edu.office.tools.PersonalSessionSetup;
import edu.office.tools.Tool;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.*;

@Named("studentdreamRepositoryA")
@ApplicationScoped
public class StudentdreamRepository extends ApplicationCommonRepository<Studentdream>{
    private final String tableName = "studentDream", foldName = "studentDream";
    @Inject
    StudentRepository applicationStudentRepository;
    @Inject
    PersonalSessionSetup personalSessionSetup;
    @Inject
    SubjectRepository subjectRepository;
    WordsSegment ws = new WordsSegment();

    public String mycreate(Part picture, Studentdream studentdream, List<Subject> subjects2study) {
        try {
            String fileName = storePicture(picture, studentdream.getSTUID());
            if (null != fileName) {
                studentdream.setMEDIA(fileName);
            }
            this.updateSubject(subjects2study);
            create(studentdream);
            return EOMessage.getEOMessageENUM(EOMessage1.Succeed);
        } catch (Exception e) {
            return EOMessage.getEOMessageENUM(EOMessage1.Failed);
        }
    }

    private String updateSubject(List<Subject> subjects2study) {
        StringBuilder sb = new StringBuilder();
        //更新所学课程
        if (null != subjects2study && !subjects2study.isEmpty()) {
            for (Subject subject : subjects2study) {
                sb.append(",").append(subject.getID());
            }
        }
        if (sb.isEmpty()) return "";
        else return sb.toString();
    }

    public void update(Part picture, Studentdream studentdream, List<Subject> subjects2study) {
        try {
            String fileName = storePicture(picture, studentdream.getSTUID());
            if (null != fileName) {
                studentdream.setMEDIA(studentdream.getMEDIA() + "," + fileName);
            }
            this.updateSubject(subjects2study);
            edit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<String> getPictures(Studentdream studentdream) {//把图片名称封闭成list
        List<String> pictures = new LinkedList<>();
        if (studentdream.getMEDIA() != null) {
            if (studentdream.getMEDIA().trim().length() > 0) {
                String[] tem = studentdream.getMEDIA().split(",");
                for (int i = 0; i < tem.length; i++) {
                    pictures.add(tem[i]);
                }
            }
        }

        return pictures;
    }

    //下面是为表格处理
    private String storePicture(Part picture, Integer student) {
        String fileName = null;
        if (picture != null) {
            InputStream in = null;
            try {
                in = picture.getInputStream();
                File file = new File(personalSessionSetup.getFilePath() + "/" + foldName);
                if (!file.exists()) {
                    file.mkdirs();
                }
                fileName = student + "_" + picture.getSubmittedFileName() + "."
                        + Tool.getExtension(picture.getSubmittedFileName());
                Files.copy(in, new File(personalSessionSetup.getFilePath() + "/" + foldName + "/" + fileName).toPath());
            } catch (IOException ex) {
                System.out.println("studentDreamController--storePicture");
            }
        }
        return fileName;
    }

    public void deleteFiles(String deletePicturename, Studentdream studentdream) {
        StringBuffer pictureNames = new StringBuffer();
        String[] pictures = studentdream.getMEDIA().split(",");
        for (String picture : pictures) {
            pictureNames.append(picture);
        }
        //找到前台传过来的值，从stringBuffer中删除掉,首先判断数据库中如果只有一个视频的话，则需要删除掉该条资源

        int index = pictureNames.indexOf(deletePicturename);
        pictureNames.delete(index, index + deletePicturename.length() + 1);
        if (pictureNames.charAt(pictureNames.length() - 1) == ',') {
            pictureNames.delete(pictureNames.length() - 1, pictureNames.length());
        }
        studentdream.setMEDIA(pictureNames.toString().trim());
        //更新当前知识点
        edit();
        //删除服务器中的文件
        File f = new File(personalSessionSetup.getFilePath() + "/" + foldName + "/" + deletePicturename);
        if (f.exists()) {
            f.delete();
        }
    }

    //下面是为教师页面处理的方法
    public String getStduentNames(Set<Integer> ids) {//这里的id是studentdream的id
        String result = "";
        HashSet<Student> students = new HashSet<>();//避免重复统计学生
        for (Integer id : ids) {
            students.add(applicationStudentRepository.find("ID", find("ID", id).firstResult().getSTUID()).firstResult());
        }
        for (Student student : students) {
            result += student.getSecondname() + student.getFirstname() + ",";
        }
        return result;
    }

    public List<Studentdream> getStudentDream4Teacher(School school) {
        List<Studentdream> allStudentdreams = new LinkedList<>();
        for (Student student : applicationStudentRepository.list("SCHOOL_ID", school)) {
            allStudentdreams.addAll(list("STUID", student));
        }
        //下面进行统计
        Map<Integer, String> idContent = new HashMap<>();
        for (Studentdream studentdream : allStudentdreams) {
            idContent.put(studentdream.getID(), //studentdream.getMedia() + "," +
                    studentdream.getPLAN() + "," + studentdream.getTITLE()
                            + studentdream.getMYDREAM());
        }
        WordsSegment ws = new WordsSegment();
        ws.setKeyContents(idContent);
        System.out.println("词云也准备好了");
        return allStudentdreams;
    }
    public Map<String, Integer> getWordCount() {
        return ws.getWordCount();
    }
    public String getWordCloud() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Integer> entry : getWordCount().entrySet()) {
            sb.append(entry.getKey())
                    .append(",")//用","分隔key与value
                    .append(entry.getValue() * 10)
                    .append("#");//用#分隔不同的词汇
        }
        String wordCloud = sb.toString();
        if (wordCloud.contains("#")) {
            wordCloud = wordCloud.substring(0, wordCloud.length() - 1);
        }
        return wordCloud;
    }


    public boolean fileValidate(Part file) {
        String msgs = "";
        if (null != file) {
            if (!file.getContentType().contains("image")) {
                return false;
            }
            if (file.getSize() > 1024000) {
                return false;
            }
        }
        return true;
    }

    public void setSubjects2study(List<Object> paraSubjects2study) {
        //这个时候传上来的是Integer的List，需要转换
        List<Subject> subjects2study=new LinkedList<>();//要学的课程
        for (int i = 0; i < paraSubjects2study.size(); i++) {
            if (paraSubjects2study.get(i) instanceof Subject) {
                subjects2study.add((Subject) paraSubjects2study.get(i));
            } else if (paraSubjects2study.get(i) instanceof Integer) {
                subjects2study.add(subjectRepository.findById((Integer) paraSubjects2study.get(i)));
            }
        }
    }

}
